const Koa = require('koa')
const axios = require('axios')
const cheerio = require('cheerio')

const app = new Koa()

function substri(str, startStr, endStr, x){
	// x: 0->(),  1->[],  2-> [), 3->(]
	let pos_s, pos_e, pos_start, pos_end
	pos_s = str.indexOf(startStr)
	pos_e = str.indexOf(endStr)
	
	switch(x) {
		case 0:
			pos_start = pos_s + startStr.length
			pos_end = pos_e
			break
		case 1:
			pos_start = pos_s
			pos_end = pos_e + endStr.length
			break
		case 2:
			pos_start = pos_s
			pos_end = pos_e
			break
		case 3:
			pos_start = pos_s + startStr.length
			pos_end = pos_e + endStr.length
			break
	}

	return str.slice(pos_start, pos_end)
}

function sleep(ms){
  return new Promise((resolve)=>setTimeout(resolve,ms));
}

app.use(async (ctx, next) => {

	let goods = []
	const { status, data } = await axios.get("https://market.douban.com/api/v2/market/products?name=all&start=0&count=31")
	data.data.products.map((item, idx) => {
		let obj = {
			base_data: {
				product_id: item.id,
				title: item.title,
				desc: item.desc,
				p_detail: {},
				m_detail: {},
				photos: {
					defaultimg: item.image,
					galleary: []
				},
				salinfo: [],
				total_stock: '',
				url: item.url,
				price: item.price,
				promote_price: item.promote_price,
				sale_sort: item.sale_props_sort,
				skus: []
			},
			assistant_data: {
				category: [],
				series: [],
				isNew: {
					isNew: false,
					img: ''
				},
				isHot: {
					isHot: false,
					img: '',
				},
				isIndexSlider: {
					isIndexSlider: false,
					img: item.activity_image
				}
			}
		}
		goods.push(obj)
	})

	const category = {
		classic: 'https://market.douban.com/api/v2/market/category/classic?name=classic&start=0&count=31',
		homelie: 'https://market.douban.com/api/v2/market/category/homelife?name=homelife&start=0&count=31',
		travel: 'https://market.douban.com/api/v2/market/category/travel?name=travel&start=0&count=31',
		stationery: 'https://market.douban.com/api/v2/market/category/stationery?name=stationery&start=0&count=31'
	}
	
	
	
	for(let i in category){
		const { status, data } = await axios.get(category[i])
		goods.forEach((item, idx) => {
			let x = data.data.products.some((ite, ix) => {
				return item.base_data.product_id === ite.id
			})
			if(x===true) {
				item.assistant_data.category.push(i)
			}
		})
	}


	for(let i =0; i<goods.length; i++){   
		const { status, data } = await axios.get(goods[i].base_data.url)
		let str = substri(data, "var _CONFIG = ", " 'min_qua_gift': '',\n      }\n    }\n  }", 3)
		
		// \n \t \ 注释部分
		
		str = str.replace(/\n/g, '')
		str = str.replace(/\t/g, '')
		//str = str.replace(", // 区分产品线 market/movie 等，用来控制页面底部「购物说明」      'is_reserved': false, // 是否已经预订      'stock_filling': 0, // 是否正在补货中      'reserve_enabled': false, // 商品是否可以预订      'onsale_date': ''    },    'selector': {      'checkout': \"\", // 手动控制按钮文案    ", "")
		//console.log(i)
		str = str.replace(substri(str, ", // 区分产品线 market", "// 手动控制按钮文案    ", 1), '')
		str = str.replace(/'/g, '\"')
		str = str.replace('"min_qua_gift": "", ', '"min_qua_gift": ""')
		
		str = JSON.parse(str)
		
		goods[i].base_data.p_detail = str.page.pc_contents
		goods[i].base_data.m_detail = str.page.mobile_contents
		goods[i].base_data.head_img = str.page.head_img
		goods[i].base_data.skus = str.skus
		goods[i].base_data.total_stock = str.page.total_stock
		goods[i].assistant_data.price_info = str.price_info
		
	}


	
	


	ctx.response.type = 'text/json'
		ctx.response.body = {
			goods
		}
})	




// 在端口3000监听:
app.listen(3000)
console.log('app started at port 3000...')


/*
https://market.douban.com/api/v2/market/products?name=all&start=0&count=31
https://market.douban.com/api/v2/market/category/classic?name=classic&start=0&count=12
https://market.douban.com/api/v2/market/category/homelife?name=homelife&start=0&count=12
https://market.douban.com/api/v2/market/category/travel?name=travel&start=0&count=12
https://market.douban.com/api/v2/market/category/stationery?name=stationery&start=0&count=12





*/